package cn.lijiguo.concurrency.part1.threadobjectmethods;

/**
 * WaitNotifyAll
 * 三个线程 线程1 和 线程 2 被阻塞，线程 3 唤醒他们 notify() notifyAll()
 * start() 先执行 并不代表 线程先启动
 * @author lijiguo
 * @date 2020/1/6 16:07
 */
public class WaitNotifyAll implements Runnable {

    public static Object resourceA = new Object();

    public static void main(String[] args) throws InterruptedException {
        WaitNotifyAll r = new WaitNotifyAll();

        Thread t1 = new Thread(r, "t1");
        Thread t2 = new Thread(r, "t2");
        Thread t3 = new Thread(() -> {
            synchronized (resourceA) {
                resourceA.notifyAll();
                System.out.println(Thread.currentThread().getName() + " notified.");
            }
        }, "t3");

        t1.start();
        t2.start();
        Thread.sleep(200);
        t3.start();
    }

    @Override
    public void run() {
        synchronized (resourceA) {
            System.out.println(Thread.currentThread().getName() + " got resourceA lock.");

            try {
                System.out.println(Thread.currentThread().getName() + " waits to start.");
                resourceA.wait();
                System.out.println(Thread.currentThread().getName() + "'s waiting to end.");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
